﻿/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

using System.Xml;

namespace Daidalos.GameObjects
{
	public sealed class GameMap
	{
		
		#region Attributes
		/// <summary>
		///		The name of the map.
		/// </summary>
		private string name = null;

		/// <summary>
		///		The map's author.
		/// </summary>
		private string author = null;

		/// <summary>
		///		The width of the terrain in cells.
		/// </summary>
		private int terrainWidth;

		/// <summary>
		///		The height of the terrain in cells.
		/// </summary>
		private int terrainHeight;
		#endregion

		#region Properties
		#endregion

		#region Constructors
		/// <summary>
		///		Creates a terrain object from a terrain
		///		file specified by its name.
		/// </summary>
		/// <param name="name">
		///		The name of the desired terrain file.
		/// </param>
		public GameMap(string name)
		{
			// Try to parse the map file.
			string xmlName = name + ".xml";
			ParseMeta(xmlName);

			// Determine the map-name.
			string mapName = name + ".map";
			ParseGeometry(mapName);
		}
		#endregion

		#region Methods
		/// <summary>
		///		This method loads the terrain geometry
		///		from a map file.
		/// </summary>
		/// <param name="name">
		///		The map file containing the terrain
		///		geometry.
		/// </param>
		private void ParseGeometry(string name)
		{
			// Try to open the file.
            VFS.BinaryFile reader = (VFS.BinaryFile)VFS.Vfs.Instance.OpenFile(name, Daidalos.VFS.OpenMode.READ, Daidalos.VFS.FileMode.BINARY);

			// Try to allocate a texture buffer.
			float[] ztexture = new float[terrainWidth * terrainHeight];
			if (ztexture == null)
			{
				throw new Exception("Failed to allocate the software texture buffer!");
			}

			// Load the software buffer.
			try
			{
				for (int h = 0; h < terrainHeight; ++h)
				{
					for (int w = 0; w < terrainWidth; ++w)
					{
						// Determine buffer index.
						int index = terrainWidth * h + w;

						// Perform Z-Texture fetch.
                        ztexture[index] = reader.ReadFloat();
					}
				}
			}
			catch (System.Exception e)
			{
                reader.Close();
				throw new Exception(e.ToString());
			}
            reader.Close();
		}

		/// <summary>
		///		This method parses the map meta information
		///		stored in an XML file.
		/// </summary>
		/// <param name="name">
		///		The name of the XML file.
		/// </param>
		private void ParseMeta(string name)
		{
			// Create an XmlDocument object.
			XmlDocument xml = new XmlDataDocument();
			if (xml == null)
			{
				throw new Exception("Failed to create an XmlDocument-object!");
			}

			// Load the meta file into the object.
			xml.Load(name);

			// Extract the root element.
			XmlElement root = xml.DocumentElement;

			// Verify the presence of child nodes.
			if (root == null || !root.HasChildNodes)
			{
				throw new Exception("Incomplete or damaged map file!");
			}

			// Read meta tag.
			XmlNode meta = root.SelectSingleNode("meta");
			if (meta == null)
			{
				throw new Exception("Map file lacks meta information!");
			}

			// Retrieve the name and author.
			name = meta.Attributes["name"] == null ? "Unnamed map" : meta.Attributes["name"].Value;
			author = meta.Attributes["author"] == null ? "No author" : meta.Attributes["author"].Value;

			// Read terrain tag.
			XmlNode terrain = root.SelectSingleNode("terrain");
			if (terrain == null)
			{
				throw new Exception("Map file lacks terrain information!");
			}

			// Retrieve the dimensions
			if (terrain.Attributes["width"] == null || terrain.Attributes["height"] == null)
			{
				throw new Exception("Malformed or missing size information!");
			}
			terrainWidth = int.Parse(terrain.Attributes["width"].Value);
			terrainHeight = int.Parse(terrain.Attributes["height"].Value);
		}
		#endregion

	}
}
